package com.ahcloud.enhance.redisson.configuration;

import com.ahcloud.enhance.lock.base.LockUtils;
import com.ahcloud.enhance.redisson.lock.RedissonILock;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;
import java.util.List;

/**
 * @program: distributedlock-enhance
 * @description:
 * @author: YuKai Fan
 * @create: 2024/4/30 22:30
 **/
@Configuration
@EnableConfigurationProperties(RedissonProperties.class)
public class RedissonAutoConfiguration {

    private final List<RedissonAutoConfigurationCustomizer> customizers;

    @Autowired(required = false)
    public RedissonAutoConfiguration(List<RedissonAutoConfigurationCustomizer> customizers) {
        this.customizers = customizers;
    }

    @Bean(destroyMethod = "shutdown")
    @ConditionalOnProperty(prefix = "distributed.lock", name = "type", havingValue = "redisson", matchIfMissing = true)
    public RedissonClient redisson(RedissonProperties properties) throws IOException {
        Config config;
        try {
            config = Config.fromYAML(properties.getConfig());
        } catch (IOException e) {
            throw new IllegalArgumentException("Can't parse config", e);
        }
        if (customizers != null) {
            for (RedissonAutoConfigurationCustomizer customizer : customizers) {
                customizer.customize(config);
            }
        }
        return Redisson.create(config);
    }

    @Bean
    @ConditionalOnBean(RedissonClient.class)
    public RedissonILock redissonLock(RedissonClient redisson) {
        RedissonILock lock = new RedissonILock(redisson);
        LockUtils.setLocker(lock);
        return lock;
    }
}
